"""数据库模型"""
from web.setting import db
from datetime import datetime
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash


class SaveData:
    def save(self):
        db.session.add(self)
        db.session.commit()


class DeleteData:
    def delete(self):
        db.session.delete(self)
        db.session.commit()


class User(db.Model, UserMixin, SaveData, DeleteData):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True, nullable=False)
    username = db.Column(db.String(20), nullable=False, index=True, comment='用户名')
    password_hash = db.Column(db.String(300), nullable=False, comment='密码')
    register_time = db.Column(db.DateTime, nullable=True, index=True, default=datetime.now, comment='注册时间')
    login_time = db.Column(db.DateTime, index=True, comment='登录时间')
    authority = db.Column(db.Integer, nullable=False, default=1, comment='权限')
    authority_name = db.Column(db.String(20), nullable=False, default='普通用户', comment='权限名称')

    @property
    def password(self):
        raise AttributeError('password is not a readable attribute')

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password, method='pbkdf2:sha256', salt_length=10)

    def check_password(self, password):
        """
            检查密码是否正确
            参数:password (str): 要检查的密码
            返回:bool: 密码是否正确
        """
        return check_password_hash(self.password_hash, password)

    def __repr__(self):
        return '<User {}>'.format(self.username)


class MovieData(db.Model, SaveData, DeleteData):
    __tablename__ = 'movie_data'
    id = db.Column(db.Integer, primary_key=True, nullable=False)
    title = db.Column(db.String(200), nullable=False, index=True, comment='影视名')
    movie_type = db.Column(db.String(50), nullable=False, comment='类型')
    year = db.Column(db.Integer, nullable=False, index=True, comment='年份')
    director = db.Column(db.String(200), nullable=False, comment='导演')
    film_length = db.Column(db.Integer, nullable=False, comment='时长')
    score = db.Column(db.Float, nullable=False, comment='评分')
    people_num = db.Column(db.Integer, nullable=False, index=True, comment='评价人数')
    info_url = db.Column(db.String(230), nullable=False, comment='影视详情页地址')
    img_url = db.Column(db.String(230), nullable=False, comment='图片地址')


class SpiderRunInfo(db.Model, SaveData, DeleteData):
    __tablename__ = 'spider_run_info'
    id = db.Column(db.Integer, primary_key=True, nullable=False)
    run_time = db.Column(db.DateTime, nullable=False, index=True, default=datetime.now,
                         comment='爬虫运行时间')
    run_user = db.Column(db.String(20), nullable=False, comment='爬虫运行用户')
    run_ip = db.Column(db.String(20), nullable=False, default='127.0.0.1', comment='爬虫运行IP')
